#!/usr/bin/perl
#
# $Log$
# Revision 1.5  2010/03/20 16:12:00  tm
# first version of SpamAssassin check script
#
#

$statefile = $ENV{statefile} || "/opt/local/var/munin/plugin-state/munin-spamstats.state";
$pos   = undef;
$ham = 0;
$spam = 0;

$logfile = $ENV{logdir} || "/var/log/";
$logfile .= $ENV{logfile} || "maillog";

if ( $ARGV[0] and $ARGV[0] eq "config" )
{
	print "host_name $ENV{FQDN}\n";
	print "graph_title SpamAssassin throughput\n";
	print "graph_args --base 1000 -l 0\n";
	print "graph_vlabel mails/\${graph_period}\n";
	print "graph_order ham spam\n";
	print "graph_category mail\n";
	print "ham.label ham\n";
	print "ham.type DERIVE\n";
	print "ham.min 0\n";
	print "ham.draw AREA\n";
	print "spam.label spam\n";
	print "spam.type DERIVE\n";
	print "spam.min 0\n";
	print "spam.draw STACK\n";
	exit 0;
}

if (!-f "$logfile")
{
	print "ham.value U\n";
	print "spam.value U\n";
	exit 0;
}

if (-f "$statefile")
{
	open (IN, "$statefile") or exit 4;
	if (<IN> =~ /^(\d+):(\d+):(\d+)/)
	{
	($pos, $ham, $spam) = ($1, $2, $3);
	}
	close IN;
}

$startsize = (stat $logfile)[7];

if (!defined $pos) {
	# Initial run.
	$pos = $startsize;
}

if ($startsize < $pos) {
	# Log rotated
	parselogfile ($logfile, $pos, (stat $logfile)[7]);
	$pos = 0;
}

parselogfile ($logfile, $pos, $startsize);
$pos = $startsize;

print "ham.value $ham\n";
print "spam.value $spam\n";

open (OUT, ">$statefile") or exit 4;
print OUT "$pos:$ham:$spam\n";
close OUT;

sub parselogfile {
	my ($fname, $start, $stop) = @_;
	open (LOGFILE, $fname) or exit 3;
	seek (LOGFILE, $start, 0) or exit 2;

	while (tell (LOGFILE) < $stop) {
		my $line =<LOGFILE>;
		chomp ($line);

		if ($line =~ m/clean message/) {
			$ham++;
		} 
		elsif ($line =~ m/identified spam/) {
			$spam++;
		}
	}
	close(LOGFILE);	
}
